package com.tnsw.noxnox;

import java.io.RandomAccessFile;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.google.android.gcm.GCMRegistrar;
import com.tnsw.coreutils.AsyncManager;
import com.tnsw.coreutils.files.FileUtils;
import com.tnsw.coreutils.http.THttpBase;
import com.tnsw.coreutils.http.THttpGet;
import com.tnsw.coreutils.http.THttpListener;
import com.tnsw.coreutils.text.TextUtils;
import com.tnsw.noxnox.db.DBManager;
import com.tnsw.noxnox.db.DBManagerBase;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.net.UrlQuerySanitizer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.view.ViewGroup;
import android.widget.Button;

public class SignupActivityOld extends Activity implements THttpListener, Runnable, AccountManagerCallback<Bundle>, OnClickListener, DialogInterface.OnClickListener {

	// https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.AHES6ZROyjGXrdKrxrw5x1y5aDFCoQDg8ZR-XSH7FYX8mkud
	
	// https://gdata.youtube.com/feeds/api/videos?q=Korean&key=AI39si7E89SyqZrykCrFXwXMu5UKWxWabzCu8-RdFRhcEeALZ1dY-Ry77Ze_ExuB3ezCHnjc7z4r_F9iEtN2B9wXYzc-xW5wwQ
	
	// https://www.googleapis.com/oauth2/v1/userinfo
	
	//private String AUTH = "oauth2:https://www.google.com/m8/feeds/contacts/default/full";
	private String AUTH = "oauth2:https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://gdata.youtube.com";
	private String YOUTUBE_DEVKEY = "AI39si7E89SyqZrykCrFXwXMu5UKWxWabzCu8-RdFRhcEeALZ1dY-Ry77Ze_ExuB3ezCHnjc7z4r_F9iEtN2B9wXYzc-xW5wwQ";
	
	private String tag = "SignupActivity";
	private Button btnLogin, btnClear, btnGoogle, btnRegister, btnUnregister, btnYoutube, btnGoYoutube;
	private AccountManager accountManager;
	private Account selectedAccount;
	
	private ArrayList<Account> accounts;
	private String[] facebookAccountType = {"com.facebook.auth.login"};
	private String[] googleAccountType = {"com.android.email", "com.google"};
	
	private ProgressDialog dlgProgress;
	
	private Intent passwordIntent = null;
	
	public AsyncManager asyncManager;
	public static String[] YOUTUBE_PARAMS = {"factor", "algorithm", "burst", "newshard", "ratebypass", "gcr", "ipbits", "id", "sver", "ip", "cp", "ms", "fexp", "mv", "upn", "mt", "sparams", "source", "key", "expire", "itag", "signature"};

	public SignupActivityOld() {
		Log.d(tag, "Constructor()");
		this.asyncManager = AsyncManager.getInstance();
		
		
	}
	
	private void testsomething() {
		String urlEncode = "itag=46&fallback_host=tc.v7.cache5.c.youtube.com&sig=72D6164F320993C801F80378304543F26BF446E7.9F09AB79BD7955D3B702395244D34149ED6198F4&type=video%2Fwebm%3B+codecs%3D%22vp8.0%2C+vorbis%22&quality=hd1080&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fipbits%3D8%26itag%3D46%26ip%3D182.52.2.248%26key%3Dyt1%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26newshard%3Dyes%26ratebypass%3Dyes%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26sparams%3Dcp%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26gcr%3Dth%26upn%3DiBYZeiws6OM,itag=37&fallback_host=tc.v17.cache7.c.youtube.com&sig=B042980B1FD15A29D0C4593B9ACA3C8F37CA34A9.AD11BD86DEBD232DB4335955642E9F59D45AB4AB&type=video%2Fmp4%3B+codecs%3D%22avc1.64001F%2C+mp4a.40.2%22&quality=hd1080&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fipbits%3D8%26itag%3D37%26ip%3D182.52.2.248%26key%3Dyt1%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26newshard%3Dyes%26ratebypass%3Dyes%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26sparams%3Dcp%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26gcr%3Dth%26upn%3DiBYZeiws6OM,itag=45&fallback_host=tc.v18.cache5.c.youtube.com&sig=93F204D5CF05122CC96C0B545C551593048B6BA1.7957C5F556D181F2FE21C5BD9E4C0B21692CA962&type=video%2Fwebm%3B+codecs%3D%22vp8.0%2C+vorbis%22&quality=hd720&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fipbits%3D8%26itag%3D45%26ip%3D182.52.2.248%26key%3Dyt1%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26newshard%3Dyes%26ratebypass%3Dyes%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26sparams%3Dcp%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26gcr%3Dth%26upn%3DiBYZeiws6OM,itag=22&fallback_host=tc.v3.cache1.c.youtube.com&sig=8FA2C426B6220C3E5AED96F9CB83208FA4A1E26B.8B79E744561074127A39653163D42FC01DBCCDDF&type=video%2Fmp4%3B+codecs%3D%22avc1.64001F%2C+mp4a.40.2%22&quality=hd720&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fipbits%3D8%26itag%3D22%26ip%3D182.52.2.248%26key%3Dyt1%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26newshard%3Dyes%26ratebypass%3Dyes%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26sparams%3Dcp%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26gcr%3Dth%26upn%3DiBYZeiws6OM,itag=44&fallback_host=tc.v3.cache5.c.youtube.com&sig=2153B3930545F900F4446AF4F6A3C928541638C6.5C78DD4ED143B7650D9D8330B55DD06B9B75A159&type=video%2Fwebm%3B+codecs%3D%22vp8.0%2C+vorbis%22&quality=large&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fipbits%3D8%26itag%3D44%26ip%3D182.52.2.248%26key%3Dyt1%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26newshard%3Dyes%26ratebypass%3Dyes%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26sparams%3Dcp%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26gcr%3Dth%26upn%3DiBYZeiws6OM,itag=35&fallback_host=tc.v1.cache3.c.youtube.com&sig=30C6780C8CCBBDA22D083B44E8C1D0775DF7218A.783B6A7E45B5265540B118B0CD3CCDE71C01B1ED&type=video%2Fx-flv&quality=large&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fsparams%3Dalgorithm%252Cburst%252Ccp%252Cfactor%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Csource%252Cupn%252Cexpire%26ipbits%3D8%26itag%3D35%26ip%3D182.52.2.248%26key%3Dyt1%26factor%3D1.25%26newshard%3Dyes%26gcr%3Dth%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26algorithm%3Dthrottle-factor%26burst%3D40%26upn%3DiBYZeiws6OM,itag=43&fallback_host=tc.v18.cache5.c.youtube.com&sig=7D357DD9B0B8F256CA85EAA14FFAEEA0B579B18B.AC81311536EBC10A14F6FC3C531FCC6CE100336D&type=video%2Fwebm%3B+codecs%3D%22vp8.0%2C+vorbis%22&quality=medium&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fipbits%3D8%26itag%3D43%26ip%3D182.52.2.248%26key%3Dyt1%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26newshard%3Dyes%26ratebypass%3Dyes%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26sparams%3Dcp%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26gcr%3Dth%26upn%3DiBYZeiws6OM,itag=34&fallback_host=tc.v22.cache1.c.youtube.com&sig=D5836EBC33927B9006367A791F2A52DFDC7CDFE1.A06984DF8CDCA5F0ACF441E9B4BDCC0489853795&type=video%2Fx-flv&quality=medium&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fsparams%3Dalgorithm%252Cburst%252Ccp%252Cfactor%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Csource%252Cupn%252Cexpire%26ipbits%3D8%26itag%3D34%26ip%3D182.52.2.248%26key%3Dyt1%26factor%3D1.25%26newshard%3Dyes%26gcr%3Dth%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26algorithm%3Dthrottle-factor%26burst%3D40%26upn%3DiBYZeiws6OM,itag=18&fallback_host=tc.v20.cache4.c.youtube.com&sig=93A1E860FD4716A70BCA7590A3C2FAB030F8A9C8.9A91CBE65FBB167B51DA3DD4A1BF220538E9711A&type=video%2Fmp4%3B+codecs%3D%22avc1.42001E%2C+mp4a.40.2%22&quality=medium&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fipbits%3D8%26itag%3D18%26ip%3D182.52.2.248%26key%3Dyt1%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26newshard%3Dyes%26ratebypass%3Dyes%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26sparams%3Dcp%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26gcr%3Dth%26upn%3DiBYZeiws6OM,itag=5&fallback_host=tc.v11.cache8.c.youtube.com&sig=094F38729B9A7929672696242A04B6719B57D33C.D1226998EF4894AB4545C2A5A40F7781C904B3B8&type=video%2Fx-flv&quality=small&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fsparams%3Dalgorithm%252Cburst%252Ccp%252Cfactor%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Csource%252Cupn%252Cexpire%26ipbits%3D8%26itag%3D5%26ip%3D182.52.2.248%26key%3Dyt1%26factor%3D1.25%26newshard%3Dyes%26gcr%3Dth%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26algorithm%3Dthrottle-factor%26burst%3D40%26upn%3DiBYZeiws6OM,itag=36&fallback_host=tc.v14.cache1.c.youtube.com&sig=2B75F82AB516A4297609086CD09512552B7219C7.0A1D72AB5E9C7C1ECC580B1C90AFD0CED48243AA&type=video%2F3gpp%3B+codecs%3D%22mp4v.20.3%2C+mp4a.40.2%22&quality=small&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fsparams%3Dalgorithm%252Cburst%252Ccp%252Cfactor%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Csource%252Cupn%252Cexpire%26ipbits%3D8%26itag%3D36%26ip%3D182.52.2.248%26key%3Dyt1%26factor%3D1.25%26newshard%3Dyes%26gcr%3Dth%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26algorithm%3Dthrottle-factor%26burst%3D40%26upn%3DiBYZeiws6OM,itag=17&fallback_host=tc.v12.cache4.c.youtube.com&sig=9CF4963032F543638CDD6BDEC348441A2780FDB8.349831A7451AB8E626308BB7631ABCF56733B519&type=video%2F3gpp%3B+codecs%3D%22mp4v.20.3%2C+mp4a.40.2%22&quality=small&url=http%3A%2F%2Fr6---sn-uvu-c33el.c.youtube.com%2Fvideoplayback%3Fsparams%3Dalgorithm%252Cburst%252Ccp%252Cfactor%252Cgcr%252Cid%252Cip%252Cipbits%252Citag%252Csource%252Cupn%252Cexpire%26ipbits%3D8%26itag%3D17%26ip%3D182.52.2.248%26key%3Dyt1%26factor%3D1.25%26newshard%3Dyes%26gcr%3Dth%26fexp%3D902904%252C906370%252C904821%252C916807%252C914050%252C916623%252C920704%252C912806%252C902000%252C922403%252C922405%252C929901%252C913605%252C925006%252C931202%252C908529%252C920201%252C930101%252C906834%252C901451%26ms%3Dau%26source%3Dyoutube%26cp%3DU0hVRlhOTl9LS0NONV9QSFJIOkJzSmxjYV9NeXg3%26mv%3Dm%26sver%3D3%26id%3Df5b664a7bab5f5fd%26expire%3D1361830761%26mt%3D1361807956%26algorithm%3Dthrottle-factor%26burst%3D40%26upn%3DiBYZeiws6OM";
		//urlEncode = urlEncode.replace("%25", "%");
		//urlEncode = URLDecoder.decode(urlEncode);
		this.getUrls(urlEncode);
		
		
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //this.testsomething();
        
        setContentView(R.layout.signup_layout);
        DBManager dbm = (DBManager) DBManager.getInstance(this);
        
        this.accountManager = AccountManager.get(this);
        
        this.btnLogin = (Button) this.findViewById(R.id.btnLogin);
        this.btnLogin.setOnClickListener(this);
        
        this.btnClear = (Button) this.findViewById(R.id.btnClear);
        this.btnClear.setOnClickListener(this);
        
        this.btnGoogle = (Button) this.findViewById(R.id.btnGoogle);
        this.btnGoogle.setOnClickListener(this);
        
        this.btnRegister = (Button) this.findViewById(R.id.btnRegister);
        this.btnRegister.setOnClickListener(this);
        
        this.btnUnregister = (Button) this.findViewById(R.id.btnUnregister);
        this.btnUnregister.setOnClickListener(this);
        
        this.btnYoutube = (Button) this.findViewById(R.id.btnYoutube);
        this.btnYoutube.setOnClickListener(this);
        
        this.btnGoYoutube = (Button) this.findViewById(R.id.btnGoYoutube);
        this.btnGoYoutube.setOnClickListener(this);
        
        this.accounts = this.createAccountsList(this.facebookAccountType, accounts);
        this.accounts = this.createAccountsList(this.googleAccountType, accounts);
        
        this.dlgProgress = new ProgressDialog(this);
        this.dlgProgress.setMessage("Loading..");
        this.dlgProgress.setTitle("");
        
        Log.d(tag, "accounts:");
        for (Account ac : this.accounts) {
        	Log.d(tag, ac.name + " " + ac.type);
        }
        
        Log.d(tag, "Done: onCreate()");
    }
    
    private ArrayList<Account> createAccountsList(String[] lists, ArrayList<Account> existingArrayList) {
    	ArrayList<Account> aa = null;
    	
    	if (existingArrayList == null) {
    		aa = new ArrayList<Account>();
    	} else {
    		aa = existingArrayList;
    	}
    	
    	
    	if (lists != null) {
    		if (lists.length > 0) {
    			for (String type : lists) {
    				Account[] a = this.accountManager.getAccountsByType(type);
    				if (a != null) {
    					if (a.length > 0) {
    						for (Account account : a) {
    							aa.add(account);
    						}
    					}
    				}
    				
    	    	}    	    
    	    			
    		}
    	}
    	
    	
    	return(aa);
    }

	@Override
	public void onClick(View v) {
		if (v == this.btnLogin) {
			this.showDialog(1);
			
		} else if (v == this.btnClear) {
			SharedPreferences settings = getSharedPreferences(tag, 0);
		    String token = settings.getString("token", "");
		    Log.d(tag, "trying to revoke token={" + token + "} from cache");
			this.accountManager.invalidateAuthToken("com.google", token);
			Log.d(tag, "cache clear!");
			
		} else if (v == this.btnGoogle) {
			//Thread t = new Thread(this);
			//t.start();
			DBManager dbm = DBManager.getInstance(this);
			try {
				byte[] b = FileUtils.readFile(dbm.getFullDatabasePath());
				String base64 = Base64.encodeToString(b, Base64.DEFAULT);
				this.asyncManager.appendBase64(base64, "xx.db");	
			} catch (Exception e) {
				Log.e(tag, e.toString(), e);
			}
			
			
		} else if (v == this.btnRegister) {
			try {
				GCMRegistrar.checkDevice(this);
		        GCMRegistrar.checkManifest(this);
				
		        GCMRegistrar.register(this, "518191396700");
		        this.dlgProgress.setMessage("Registering..");
		        //this.dlgProgress.setCancelable(false);
		        this.dlgProgress.show();
		        
		        
			} catch (Exception e) {
				Log.e(tag, e.toString());
			}
			
	        
		} else if (v == this.btnUnregister) {
			GCMRegistrar.unregister(this);
			Log.d(tag, "Unregistered");
			
		} else if (v == this.btnYoutube) {
			String url = "http://www.tns-wireless.com/cdr_data/original";
			url = "http://www.youtube.com/watch?v=9bZkp7q19f0";   // Psy
			//url = "http://www.youtube.com/watch?v=07Q66wzyepQ";  // Thai Series
			//url = "http://l.yimg.com/bt/api/res/1.2/KQaWBk9TeV.GQlbGF8kVig--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTI0MjtweW9mZj0wO3E9ODU7dz00MzA-/http://media.zenfs.com/es/News/efe.es/20130119-634942263430369757w.jpg";
			THttpGet g = new THttpGet(this, url);
			g.setBinaryDirection(THttpBase.BINARY_TO_FILE);
			g.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			g.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
			g.addHeader("Accept-Encoding", "gzip,deflate,sdch");
			g.addHeader("Connection", "keep-alive");
			g.addHeader("Accept-Language", "th,en-US;q=0.8,en;q=0.6");
			//g.addHeader("Host", "www.youtube.com");
			g.addHeader("Host", THttpBase.getHost(url));
			g.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4");
			g.setListener(this);
			g.execute("0");
			
		} else if (v == this.btnGoYoutube) {
			Intent i = new Intent(this.getApplicationContext(), YoutubeTest.class);
			this.startActivity(i);
		}
		
	}
	
    @Override
    protected Dialog onCreateDialog(int id) {
    	    	
    	if (id == 1) {
    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
    		builder.setTitle("Select account for login");
    	
    		String[] name =  new String[this.accounts.size()];
    		
    		int i = 0;
    		for (Account ac : this.accounts) {
    			name[i] = ac.name;
    			i += 1;
    		}
    		
    		builder.setItems(name, this);
    		
    		return(builder.create());
    	} else {
    		return(null);
    	}
    }

	@Override
	public void onClick(DialogInterface dialog, int which) {
		this.selectedAccount = this.accounts.get(which);
		Log.d(tag, "account:" + this.selectedAccount.name + " is selected");
		
    	
    	final Handler handler = new Handler(new Handler.Callback() {
			
			@Override
			public boolean handleMessage(Message msg) {

				return false;
			}
		});
    	
    	//this.am.getAuthToken(ac, AUTH, true, this, handler);
    	//AccountManagerFuture<Bundle> b = this.accountManager.getAuthToken(ac, AUTH, true, this, handler);
    	AccountManagerFuture<Bundle> b = this.accountManager.getAuthToken(this.selectedAccount, AUTH, null, true, this, handler);
    
    	Log.d(tag, "Authened?");
	}
	
	@Override
	protected void onActivityResult (int requestCode, int resultCode, Intent data) {
		//super.onActivityResult(requestCode, resultCode, data);
		

		Log.d(tag, "onActivityResult(requestCode=" + requestCode + ", resultCode=" + resultCode + ")");
				
	}

	@Override
	public void run(AccountManagerFuture<Bundle> arg0) {
		Log.d(tag, "here?");
    	try {
    		String token = arg0.getResult().getString(AccountManager.KEY_AUTHTOKEN);
    		
    		Log.d(tag, "token=" + token);
    		    		
    		SharedPreferences settings = getSharedPreferences(tag, 0);
    	    SharedPreferences.Editor editor = settings.edit();
    	    editor.putString("token", token);
    	    
    	    // Commit the edits!
    	    editor.commit();
    	    Log.d(tag, "put token {" + token + "} in SharedPref");
    		
            this.passwordIntent = (Intent) arg0.getResult().get(AccountManager.KEY_INTENT);

            if (this.passwordIntent != null) {
                this.passwordIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                this.passwordIntent.putExtra("key", "mykey1");
                
            	Log.d(tag, "launch != null, do something");
            	
                this.startActivityForResult(this.passwordIntent, 1);
                Log.d(tag, "exited");
                
                return;
            }
    		
    	} catch (Exception e) {
    		Log.e(tag, e.toString(), e);
    	}		
	}
	
	private void testYoutube() {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet("https://gdata.youtube.com/feeds/api/videos?q=Korean&key=AI39si7E89SyqZrykCrFXwXMu5UKWxWabzCu8-RdFRhcEeALZ1dY-Ry77Ze_ExuB3ezCHnjc7z4r_F9iEtN2B9wXYzc-xW5wwQ");
		
		try {
			SharedPreferences settings = getSharedPreferences(tag, 0);
		    String token = settings.getString("token", "");
		    Log.d(tag, "using token={" + token + "} from cache");
		    
			//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			//nameValuePairs.add(new BasicNameValuePair("Authorization", "auth " + token));
			
			//httpGet.addHeader("Authorization", "OAuth " + token);
			
			//httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
	        // Execute HTTP Post Request
	        HttpResponse response = httpClient.execute(httpGet);
	        
	        String ret = EntityUtils.toString(response.getEntity());
	        this.asyncManager.appendNetworkLog("um..");
	        Log.d(tag, ret);
	        this.asyncManager.appendNetworkLog(ret);
		} catch (Exception e) {
			Log.e(tag, e.toString());
		}		
	}

	private void testGoogleAPI() {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet("https://www.googleapis.com/oauth2/v1/userinfo");
		
		try {
			SharedPreferences settings = getSharedPreferences(tag, 0);
		    String token = settings.getString("token", "");
		    Log.d(tag, "using token={" + token + "} from cache");
		    
			//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			//nameValuePairs.add(new BasicNameValuePair("Authorization", "auth " + token));
			
			httpGet.addHeader("Authorization", "OAuth " + token);
			
			//httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
	        // Execute HTTP Post Request
	        HttpResponse response = httpClient.execute(httpGet);
	        
	        String ret = EntityUtils.toString(response.getEntity());
	        Log.d(tag, ret);
	        this.asyncManager.appendNetworkLog(ret);
		} catch (Exception e) {
			Log.e(tag, e.toString());
		}
	}

	@Override
	public void run() {
		
		this.testGoogleAPI();
		//this.testYoutube();
		
	}

	@Override
	public void onProgressUpdate(THttpBase httpBase, Integer[] values) {
		if (httpBase.getSessionName().equals("binary")) {
			Log.d(tag, "Progress binary:" + values[0]);
		}
	}

	@Override
	public void onPostExecute(THttpBase sender, Long result) {
		Log.d(tag, "onPostExecute in SignupActivity, result=" + result);
		if (sender.getHttpResponse() != null) {
			Log.d(tag, "HTTPResponse=" + sender.getHttpResponse().getStatusLine().getStatusCode());
			if (sender.getCurrentSB() != null) {
				asyncManager.appendNetworkLog(sender.getCurrentSB().toString());
				//Log.d(tag, sender.getCurrentSB().toString());
			} else {
				Log.e(tag, "Return StringBuffer is null!!");
				
				try {
					byte[] bb = sender.getBytes(0, 15000);
					RandomAccessFile r = new RandomAccessFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.jpg", "rw");
					r.write(bb);
					r.close();
					Log.d(tag, "Written semi..");
				} catch (Exception e) {
					Log.e(tag, e.toString(), e);
				}
				
				if (sender.getOutputStream() != null) {
					//int length = sender.getOutputStream().toByteArray().length;
					//Log.d(tag, "Binary, OutputStream.length=" + length);
					//Log.d(tag, "sdcard_path=" + Environment.getExternalStorageDirectory().getAbsolutePath());
					
					try {
						//RandomAccessFile r = new RandomAccessFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.jpg", "rw");
						//r.write(sender.getOutputStream().toByteArray(), 0, (int) length/2);											
					
						//r.close();
						
						//Log.i(tag, "written file into sdcard successfully (half)");
						
					} catch (Exception e) {
						Log.e(tag, e.toString(), e);
					}
					
					
				}
			}
			
		} else {
			
		}
		//MainActivity.asyncManager.appendNetworkLog(sender.getCurrentSB().toString());
	}

	@Override
	public void onNewLineFetchBG(THttpBase sender, String line) {
		if (line.contains("playerConfig") == true) {
			
			Log.d(tag, "true:" + line);
			asyncManager.appendNetworkLog("true");
			Log.d(tag, "Found playerConfig");
			sender.stop();
			
			Log.d(tag, "this line:" + line);
			asyncManager.appendNetworkLog(line);
			int idx = line.indexOf("=");
			String jsonStr = line.substring(idx+1, line.length()-1);
			Log.d(tag, "json=" + jsonStr);
			asyncManager.appendNetworkLog(jsonStr);
			
			try {
				JSONObject jsObj = new JSONObject(jsonStr);
				JSONObject jsArgs = jsObj.getJSONObject("args");
				String urlEncodedFmtStreamMap = jsArgs.getString("url_encoded_fmt_stream_map");
				asyncManager.appendNetworkLog("url:" + urlEncodedFmtStreamMap);
				
				String[] urls = this.getUrls(urlEncodedFmtStreamMap);
				String url = urls[3];
				
				Log.d(tag, "Downloading binary: " + url);
				
				THttpGet g = new THttpGet(this, url);
				g.setSessionName("binary");
				g.setBinaryDirection(THttpBase.BINARY_TO_FILE);
				g.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				g.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
				g.addHeader("Accept-Encoding", "gzip,deflate,sdch");
				g.addHeader("Connection", "keep-alive");
				g.addHeader("Accept-Language", "th,en-US;q=0.8,en;q=0.6");
				g.addHeader("Host", THttpBase.getHost(url));
				g.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4");
				g.setListener(this);
				//g.execute("0");
				
			} catch (Exception e) {
				Log.e(tag, e.toString(), e);
			}	
			
		}
	}
	
	private String createSingleUrl(String xUrl) {
		Uri uri = Uri.parse(xUrl);
		String prefix = uri.getScheme() + "://" + uri.getHost() + uri.getPath();
		String url = prefix;
		
		int i = 0;
		for (String param : YOUTUBE_PARAMS) {
			
			if (uri.getQueryParameter(param) != null) {
				if (i > 0) {
					url = url + "&";
				} else if (i == 0) {
					url = url + "?";
				}
				
				url = url + param + "=" + uri.getQueryParameter(param);
				
				i += 1;	
			} else {
				Log.w(tag, "createSingleUrl() -- cannot find key='" + param + "' in YOUTUBE_PARAMS");
			}
			
		}
		
		return(url);
	}
	
	private String[] getUrls(String urlEncode) {
		ArrayList<String> a = new ArrayList<String>();
		
		String keyword = urlEncode.split("=")[0];
		Log.d(tag, "getUrls, using keyword={" + keyword + "}");
		Object[] obj = TextUtils.getValueFrom(urlEncode, 0, keyword, "," + keyword);
		
		String draftUrl = (String) obj[0];
		int lastIdx = (Integer) obj[1];
		
		while (draftUrl.equals("") == false) {
			int urlIdx = draftUrl.indexOf("&url");
			String prefix = "";
			
			if ( (urlIdx == -1) && (keyword.equals("url")) ) {
				urlIdx = 0;
			}
			
			//Log.d(tag, "urlIdx=" + urlIdx);
			prefix = draftUrl.substring(0, urlIdx);
			//Log.d(tag, "prefix=" + prefix);
			
			Object[] obj2 = TextUtils.getValueFrom(draftUrl, 0, "url", "asdf1234cvbn");
			String postfix = (String) obj2[0];
			//Log.d(tag, "postfix=" + postfix);
			
			String realUrl = postfix.substring("url=".length()) + "&" + prefix;
			//Log.d(tag, "before_realUrl=" + realUrl);
			realUrl = realUrl.replace("&sig", "&signature");
			
			realUrl = realUrl.replace("%25", "%");
			realUrl = URLDecoder.decode(realUrl);
			
			Uri uri = Uri.parse(realUrl);
			
			realUrl = this.createSingleUrl(realUrl);
			
			//Log.d(tag, "realUrl=" + realUrl);
			asyncManager.appendNetworkLog("(type=" + uri.getQueryParameter("type") + ", " + uri.getQueryParameter("quality") + "), realUrl=" + realUrl);
			a.add(realUrl);
			
			obj = null;
			obj = TextUtils.getValueFrom(urlEncode, lastIdx, keyword, "," + keyword);
			draftUrl = (String) obj[0];
			lastIdx = (Integer) obj[1];
		}
				
		Log.d(tag, "getUrls, first_draftUrl=" + draftUrl + ", first_lastIdx=" + lastIdx);		
		
		String[] s = a.toArray(new String[a.size()]);
		return(s);
	}

	@Override
	public void onReceiveResponseBG(THttpBase sender) {
		
	}

	@Override
	public void onBinaryReadBG(THttpBase sender, byte[] b) {
		
	}

}
